"""
MIT License

Copyright (c) [2024] [Lin Lan]

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
__author__ = "Lin Lan or HJ--Jiao"
__email__ = "2339654498@qq.com"
__version__ = "1.0.0"

import torch
import torch.nn as nn
import math
from tqdm import tqdm
from torchvision import utils


class DoubleCovBlock(nn.Module):
    def __init__(self, in_channels: int, out_channels: int) -> None:
        """
        :param in_channels:
        :param out_channels:
        """
        super(DoubleCovBlock, self).__init__()
        self.equal = in_channels == out_channels
        self.cov1 = nn.Sequential(
            nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1),
            nn.BatchNorm2d(num_features=out_channels),
            nn.ReLU()
        )
        self.cov2 = nn.Sequential(
            nn.Conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1),
            nn.BatchNorm2d(num_features=out_channels),
            nn.ReLU()
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        :param x:
        :return:
        """
        a = self.cov1(x)
        b = self.cov2(a)
        if self.equal:
            out = x + b
        else:
            out = a + b
        return out


class TimeEmb(nn.Module):
    def __init__(self, max_step: int, dim: int) -> None:
        """
        :param max_step:
        :param dim:
        """
        super(TimeEmb, self).__init__()
        self.dim = dim
        self.max_period = max_step
        half_dim = dim // 2
        emb = math.log(max_step) / (half_dim - 1)
        emb = torch.exp(torch.arange(half_dim) * -emb)
        self.register_buffer('emb', emb)

    def forward(self, timesteps: torch.Tensor) -> torch.Tensor:
        """
        :param timesteps:
        :return:
        """
        timesteps = timesteps.float()
        sin = torch.sin(timesteps[:, None] * self.emb[None, :])
        cos = torch.cos(timesteps[:, None] * self.emb[None, :])
        time_emb = torch.cat([sin, cos], dim=-1)
        return time_emb.view(-1, self.dim, 1, 1)


class DownSample(nn.Module):
    def __init__(self, in_channels: int, out_channels: int) -> None:
        """
        :param in_channels:
        :param out_channels:
        """
        super(DownSample, self).__init__()
        self.layer = nn.Sequential(
            DoubleCovBlock(in_channels=in_channels, out_channels=out_channels),
            nn.MaxPool2d(kernel_size=2)
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        :param x:
        :return:
        """
        out = self.layer(x)
        return out


class UpSample(nn.Module):
    def __init__(self, in_channels: int, out_channels: int):
        """
        :param in_channels:
        :param out_channels:
        """
        super(UpSample, self).__init__()
        self.layer = nn.Sequential(
            nn.ConvTranspose2d(in_channels=in_channels * 2, out_channels=out_channels, kernel_size=2, stride=2),
            DoubleCovBlock(in_channels=out_channels, out_channels=out_channels)
        )

    def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
        """
        :param x:
        :param y:
        :return:
        """
        out1 = torch.cat((x, y), dim=1)
        out = self.layer(out1)
        return out


class Unet(nn.Module):
    def __init__(self, in_channels: int, image_shape: tuple, feat: int) -> None:
        """
        :param in_channels:
        :param image_shape:
        :param feat:
        """
        super(Unet, self).__init__()
        self.in_channels = in_channels
        self.image_shape = image_shape
        self.feat = feat
        assert image_shape[0] == image_shape[1], "H and W should be same"
        self.depth, self.last = self.get_depth(image_shape[0])
        self.init_cov = DoubleCovBlock(in_channels=in_channels, out_channels=feat)
        self.down = nn.ModuleList()
        for i in range(1, self.depth + 1, 1):
            self.down.append(DownSample(in_channels=feat * i, out_channels=feat * (i + 1)))
        self.down_vec = nn.Sequential(
            nn.AvgPool2d(kernel_size=self.last),
            nn.BatchNorm2d(num_features=feat * (self.depth + 1)),
            nn.ReLU()
        )
        self.up_vec = nn.Sequential(
            nn.ConvTranspose2d(in_channels=feat * (self.depth + 1), out_channels=feat * (self.depth + 1),
                               kernel_size=self.last, stride=self.last),
            nn.BatchNorm2d(num_features=feat * (self.depth + 1)),
            nn.ReLU()
        )
        self.up = nn.ModuleList()
        for i in range(self.depth + 1, 1, -1):
            self.up.append(UpSample(in_channels=feat * i, out_channels=feat * (i - 1)))
        self.out_cov = nn.Sequential(
            nn.Conv2d(in_channels=feat * 2, out_channels=feat, kernel_size=3, stride=1, padding=1),
            nn.BatchNorm2d(num_features=feat),
            nn.ReLU(),
            nn.Conv2d(in_channels=feat, out_channels=in_channels, kernel_size=3, stride=1, padding=1)
        )

    def get_depth(self, x: int) -> tuple:
        """
        :param x:
        :return:
        """
        i = 0
        while x % 2 == 0:
            i += 1
            x /= 2
        return i, int(x)

    def forward(self, x: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
        """
        :param x:
        :param t:
        :return:
        """
        init = self.init_cov(x)
        tmp_arr = [self.down[0](init)]
        for i in range(1, self.depth, 1):
            tmp_arr.append(self.down[i](tmp_arr[i - 1]))
        down = self.down_vec(tmp_arr[-1])
        up = self.up_vec(down)
        for i in range(self.depth):
            up = self.up[i](x=up, y=tmp_arr[self.depth - i - 1])
        out = torch.cat((init, up), dim=1)
        out = self.out_cov(out)
        return out


class OneUnet(Unet):
    def __init__(self, in_channels: int, image_shape: tuple, feat: int, step: int) -> None:
        """
        :param in_channels:
        :param image_shape:
        :param feat:
        :param step:
        """
        super(OneUnet, self).__init__(in_channels=in_channels, image_shape=image_shape, feat=feat)
        self.up_emb = nn.ModuleList()
        for i in range(self.depth + 1, 1, -1):
            self.up_emb.append(TimeEmb(dim=feat * i, max_step=step))

    def forward(self, x: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
        """
        :param x:
        :param t:
        :return:
        """
        init = self.init_cov(x)
        tmp_arr = [self.down[0](init)]
        for i in range(1, self.depth, 1):
            tmp_arr.append(self.down[i](tmp_arr[i - 1]))
        down = self.down_vec(tmp_arr[-1])
        up = self.up_vec(down)
        for i in range(self.depth):
            t_ = self.up_emb[i](t)
            up = self.up[i](x=up + t_, y=tmp_arr[self.depth - i - 1])
        out = torch.cat((init, up), dim=1)
        out = self.out_cov(out)
        return out


class DoubleUnet(Unet):
    def __init__(self, in_channels: int, image_shape: tuple, feat: int, step: int) -> None:
        """
        :param in_channels:
        :param image_shape:
        :param feat:
        :param step:
        """
        super(DoubleUnet, self).__init__(in_channels=in_channels, image_shape=image_shape, feat=feat)
        self.down_emb = nn.ModuleList()
        for i in range(1, self.depth + 1, 1):
            self.down_emb.append(TimeEmb(dim=feat * i, max_step=step))
        self.up_emb = nn.ModuleList()
        for i in range(self.depth + 1, 1, -1):
            self.up_emb.append(TimeEmb(dim=feat * i, max_step=step))

    def forward(self, x: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
        """
        :param x:
        :param t:
        :return:
        """
        init = self.init_cov(x)
        tmp_arr = [self.down[0](init + self.down_emb[0](t))]
        for i in range(1, self.depth, 1):
            t_ = self.down_emb[i](t)
            tmp_arr.append(self.down[i](tmp_arr[i - 1] + t_))
        down = self.down_vec(tmp_arr[-1])
        up = self.up_vec(down)
        for i in range(self.depth):
            t_ = self.up_emb[i](t)
            up = self.up[i](x=up + t_, y=tmp_arr[self.depth - i - 1])
        out = torch.cat((init, up), dim=1)
        out = self.out_cov(out)
        return out


class Diffusion(nn.Module):
    def __init__(self, model: int, beta: int, image_shape: tuple, step: int, device='cpu') -> None:
        """
        :param model:
        :param beta:
        :param image_shape:
        :param step:
        :param device:
        """
        super(Diffusion, self).__init__()
        self.model = model.to(device)
        self.image_shape = image_shape
        self.step = step
        self.device = device
        self.loss = nn.MSELoss()
        for k, v in self.set_params(beta=beta, step=step).items():
            self.register_buffer(k, v)

    def set_params(self, beta: tuple, step: int) -> dict:
        """
        :param beta:
        :param step:
        :return:
        """
        beta = torch.linspace(beta[0], beta[1], step)
        alpha = 1 - beta
        alpha_accumulate = torch.cumprod(alpha, dim=0)
        sqrt_alpha_accumulate = torch.sqrt(alpha_accumulate)
        sqrt_one_sub_alpha_accumulate = torch.sqrt(1 - alpha_accumulate)
        sqrt_beta = torch.sqrt(beta)
        div_sqrt_alpha = 1.0 / torch.sqrt(alpha)
        return {"beta": beta, "alpha_accumulate": alpha_accumulate, "sqrt_alpha_accumulate": sqrt_alpha_accumulate,
                "sqrt_one_sub_alpha_accumulate": sqrt_one_sub_alpha_accumulate, "sqrt_beta": sqrt_beta,
                "div_sqrt_alpha": div_sqrt_alpha
                }

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        :param x:
        :return:
        """
        t = torch.randint(1, self.step, (x.shape[0],)).to(self.device)
        norise = torch.randn_like(x)
        x_t = self.sqrt_alpha_accumulate[t].view(-1, 1, 1, 1) * x + self.sqrt_one_sub_alpha_accumulate[t].view(-1, 1, 1,
                                                                                                               1) * norise
        pre = self.model(x_t, t)
        the_loss = self.loss(pre, norise)
        return the_loss

    @torch.no_grad()
    def sample(self, batch_size: int) -> torch.Tensor:
        """
        :param batch_size:
        :return:
        """
        self.model.eval()
        x_t = torch.randn(size=(batch_size, *self.image_shape)).to(self.device)
        for i in tqdm(range(self.step - 1, -1, -1)):
            t = torch.Tensor([i]).type(torch.int32).repeat(batch_size).view(-1, 1, 1, 1).to(self.device)
            pre = self.model(x_t, t)
            z = torch.randn_like(x_t).to(self.device)
            x_t = self.div_sqrt_alpha[t] * (x_t - self.beta[t] * pre / self.sqrt_one_sub_alpha_accumulate[t]) + \
                  self.sqrt_beta[t] * z
        return torch.clamp(x_t, 0, 1)

    @torch.no_grad()
    def sample_save(self, batch_size: int, file_dir: str) -> None:
        """
        :param batch_size:
        :param file_dir:
        :return:
        """
        self.model.eval()
        index = self.step
        x_t = torch.randn(size=(batch_size, *self.image_shape)).to(self.device)
        for i in tqdm(range(self.step - 1, -1, -1)):
            index -= 1
            t = torch.Tensor([i]).type(torch.int32).repeat(batch_size).view(-1, 1, 1, 1).to(self.device)
            pre = self.model(x_t, t)
            z = torch.randn_like(x_t).to(self.device)
            x_t = self.div_sqrt_alpha[t] * (x_t - self.beta[t] * pre / self.sqrt_one_sub_alpha_accumulate[t]) + \
                  self.sqrt_beta[t] * z
            utils.save_image(torch.clamp(x_t, 0, 1), f"{file_dir}/{index}.png", nrow=4, normalize=True)
        del x_t
        torch.cuda.empty_cache()
